/*
 * @Description:
 * @Author: chenju
 * @Date: 2021-07-14 13:34:27
 * @LastEditors: chenju
 * @LastEditTime: 2022-03-03 15:35:13
 */
import { asyncRoutes } from '@/router'
import type { RouteRecordRaw } from 'vue-router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles: string[], route: any): boolean {
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], roles: string[]): any {
  const res: string[] = []
  routes.forEach((route: any) => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

export function generateRoutes(roles: string[]): RouteRecordRaw[] {
  let accessedRoutes = []
  if (roles.includes('admin')) {
    accessedRoutes = asyncRoutes || []
  } else {
    accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  }
  // 404 page
  accessedRoutes.push({
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    name: 'PathMatch'
  })
  return accessedRoutes
}
